package com.jifeng.httporhttps;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;

import org.apache.http.message.BasicNameValuePair;

public class HttpClienttttt {
	//private static final AllowAllHostnameVerifier HOSTNAME_VERIFIER = new AllowAllHostnameVerifier();
	 static  HostnameVerifier HOSTNAME_VERIFIER = new HostnameVerifier(){
		@Override
		public boolean verify(String hostname, SSLSession session) {
			// TODO Auto-generated method stub
			 System.out.println("Warning: URL Host: " + hostname + " vs. "
			 + session.getPeerHost());
			return true;
		}
	};
	
	private static X509TrustManager xtm = new X509TrustManager() {
		public void checkClientTrusted(X509Certificate[] chain, String authType) {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) {
			System.out.println("cert: " + chain[0].toString() + ", authType: "
					+ authType);
		}

		public X509Certificate[] getAcceptedIssuers() {
			//return null;
			return new X509Certificate[] {};
		}
	};
	
	private static X509TrustManager[] xtmArray = new X509TrustManager[] { xtm };
	private static HttpsURLConnection conn = null;
	private static HttpURLConnection con = null;
	public static String sendPOSTRequestForInputStream(String path,
			ArrayList<BasicNameValuePair> map) throws Exception {
		// 1> 组拼实体数据
		// method=save&name=liming&timelength=100
 
		StringBuilder params = new StringBuilder();
		for (int i = 0; i < map.size(); i++) {
			BasicNameValuePair NameValue = map.get(i);
			params.append(NameValue.getName());
			params.append("=");
			params.append(URLEncoder.encode(
					NameValue.getValue(), "UTF-8"));
			if(i != map.size()-1)
				params.append("&");
		}
		
		
		byte[] entity = params.toString().getBytes();
		
		
		URL url = new URL(path);
		if(CONFIG.NetFlag.equals("https")){
			conn = (HttpsURLConnection) url.openConnection();	
		if (conn instanceof HttpsURLConnection) {
			// Trust all certificates
			SSLContext context = SSLContext.getInstance("TLS");
			context.init(new KeyManager[0], xtmArray, new SecureRandom());
			SSLSocketFactory socketFactory = context.getSocketFactory();
			((HttpsURLConnection) conn).setSSLSocketFactory(socketFactory);
			((HttpsURLConnection) conn).setHostnameVerifier(HOSTNAME_VERIFIER); 
		}
		
		conn.setConnectTimeout(5 * 1000);
		conn.setRequestMethod("POST");
		conn.setDoOutput(true);// 允许输出数据 
		conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length", String.valueOf(entity.length));
		
		if(CONFIG.NetFlag.equals("https") && !CONFIG.CookieStr.equals("")){
			conn.setRequestProperty("Cookie", CONFIG.CookieStr);
		}
			
		OutputStream outStream = conn.getOutputStream();
		outStream.write(entity);
		outStream.flush();
		outStream.close();
		
		BufferedReader in;
		if (conn.getResponseCode() == 200) {
			  in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
//			  if(CONFIG.num==2){
//					HttpUtil.getCookie(conn);//获取cookie
//				}
		}else{
			  in = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
		}
		String result="";
		String line="";
		while((line=in.readLine())!=null){
			result+=line; // 得到返回结果
		} 
		in.close();
		closeConnection();
		return result;
		}else
		{
			con = (HttpURLConnection) url.openConnection(); 
//		if (conn instanceof HttpsURLConnection) {
//			// Trust all certificates
//			SSLContext context = SSLContext.getInstance("TLS");
//			context.init(new KeyManager[0], xtmArray, new SecureRandom());
//			SSLSocketFactory socketFactory = context.getSocketFactory();
//			((HttpsURLConnection) conn).setSSLSocketFactory(socketFactory);
//			((HttpsURLConnection) conn).setHostnameVerifier(HOSTNAME_VERIFIER); 
//		}
		
			con.setConnectTimeout(5 * 1000);
			con.setRequestMethod("POST");
			con.setDoOutput(true);// 允许输出数据 
			con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			//con.setRequestProperty("Charset", "gbk"); 
			con.setRequestProperty("Content-Length", String.valueOf(entity.length));

		OutputStream outStream = con.getOutputStream();
		outStream.write(entity);
		outStream.flush();
		outStream.close();
		
		BufferedReader in;
		//in = new BufferedReader(new InputStreamReader(con.getInputStream(), "gbk")); 
		/*
		if( con.getResponseMessage().indexOf("200") != -1)
		{
			in = new BufferedReader(new InputStreamReader(con.getInputStream())); 
		}
		else{
			in = new BufferedReader(new InputStreamReader(con.getInputStream())); 
		}
		*/
		
		///*
		if (con.getResponseCode() == 200) {
			  in = new BufferedReader(new InputStreamReader(con.getInputStream())); 
//			  if(CONFIG.num==2){
//					HttpUtil.getCookie(conn);//获取cookie
//				}
		}else{
			  in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
		}
		//*/
		
		String result="";
		String line="";
		while((line=in.readLine())!=null){
			result+=line; // 得到返回结果
		} 
		in.close();
		closeConnection();
		return result;
		}

	}

	public static void closeConnection() {
		if (conn != null)
			conn.disconnect();
	}
}
